from django.shortcuts import render, get_object_or_404
from .models import Post, Category
from comments.forms import CommentForm
from django.utils.text import slugify
from django.views.generic import ListView
from markdown.extensions.toc import TocExtension
import markdown


class IndexView(ListView):
    model = Post
    template_name = 'blog/index.html'
    context_object_name = 'post_list'
    # 排序
    queryset = Post.objects.order_by('-created_time')
    paginate_by = 10


def detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    # 阅读数量+1
    post.increase_views()
    md = markdown.Markdown(extensions=[
        'markdown.extensions.extra',
        'markdown.extensions.codehilite',
        'markdown.extensions.toc',
        TocExtension(slugify=slugify),
    ])
    post.body = md.convert(post.body)
    # 记得在顶部导入 CommentForm
    form = CommentForm()
    # 获取这篇 post 下的全部评论
    comment_list = post.comment_set.all()

    return render(request, 'blog/single.html', {
        'post': post,
        'form': form,
        'toc': md.toc,
        'comment_list': comment_list
    })


def archives(request, year, month):
    post_list = Post.objects.filter(created_time__year=year, created_time__month=month).order_by('-created_time')
    return render(request, 'blog/index.html', {'post_list': post_list})


def category(request, pk):
    # 记得在开始部分导入 Category 类
    cate = get_object_or_404(Category, pk=pk)
    post_list = Post.objects.filter(category=cate).order_by('-created_time')
    return render(request, 'blog/index.html', context={'post_list': post_list})


def search(request):
    q = request.GET.get('q')
    error_msg = ''

    if not q:
        error_msg = u"请输入搜索关键词"
        return render(request, 'blog/index.html', {
            'error_msg': error_msg
        })

    post_list = Post.objects.filter(title__icontains=q)
    return render(request, 'blog/index.html', {
        'error_msg': error_msg,
        'post_list': post_list
    })
